package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;

import java.util.LinkedHashMap;
import java.util.List;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Items;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Online;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Photos;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.ExportUnit;
import zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.EquipmentDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.ItemsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.OnlineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PhotosDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static zj.it.bhne.gridengineeringsurvey.fragment.OneFragment.deleteDir;
import static zj.it.bhne.gridengineeringsurvey.fragment.OneFragment.parseXMLWithPulls;

/**
 * 项目列表活动
 */
public class ItemActivity extends BaseActivity implements View.OnClickListener {

    MainAdapter adapter;
    ListView item_listView;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_item);
        context = this;

        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        item_listView = findViewById(R.id.item_listView);
        List<Items> list = MyApplication.getInstances().getItemsDao().queryBuilder().orderDesc(ItemsDao.Properties.Id).build().list();
        adapter = new MainAdapter(context, list);

        item_listView.setAdapter(adapter);

        adapter.notifyDataSetChanged();
        item_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Items items = (Items) adapter.getItem(position);
                if (items.getState().equals("在线")) {
                    //getToast(context, items.getName() + items.getId() + items.isCheck());
                    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                    map.put("surverytaskid", items.getProjectId());
                    String result = HttpConfig.callService("getProjectStatusInfo", map);
                    //Log.e("TAG", "沛星:     " + items.getProjectId() + "    " + result);
                    if (parseXMLWithPulls(result)) {
                        ToastUtils.showShort("此项目已结束勘测");
                    } else {
                        Intent intent = new Intent(context, MapActivity.class);
                        intent.putExtra("name", items.getState());
                        intent.putExtra("id", items.getId());
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(context, MapActivity.class);
                    intent.putExtra("name", items.getState());
                    intent.putExtra("id", items.getId());
                    startActivity(intent);
                }
            }
        });
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        activity_ib_back.setOnClickListener(this);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        activity_tv_title.setOnClickListener(this);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);
        activity_tv_title.setText(getString(R.string.title_xiangmu));
        activity_tv_save.setText("");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ib_back:
                finish();
                //startActivity(new Intent(context, BottomActivity.class));
                break;
        }
    }


    /**
     * 删除设备对话框
     */
    private void startDialog(final long cid, final String name, final String state, final String type) {
        final NormalDialog dialog = new NormalDialog(context);
        dialog.content("您确定要删除吗?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("删除提示")
                .btnText("取消", "删除")//
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        //删除所有相关联的数据

                        if (state.equals("在线")) {
                            Online online = MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Id.eq(type)).list().get(0);
                            online.setDown("no");
                            MyApplication.getInstances().getOnlineDao().update(online);
                            deleteItem(cid, name);
                        } else {
                            deleteItem(cid, name);
                        }

                    }
                });


    }

    private void deleteItem(long cid, String name) {
      /*  MyApplication.getInstances().getItemsDao().deleteByKey(cid);
        List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
        for (int j = 0; j < pointsList.size(); j++) {
            MyApplication.getInstances().getPointsDao().delete(pointsList.get(j));
            try {
                List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(pointsList.get(j).getId())).build().list();
                if (equipmentList.size() > 0)
                    for (int i = 0; i < equipmentList.size(); i++) {
                        MyApplication.getInstances().getEquipmentDao().delete(equipmentList.get(i));
                    }
                List<Photos> photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(pointsList.get(j).getId())).build().list();
                if (photosList.size() > 0)
                    for (int i = 0; i < photosList.size(); i++) {
                        MyApplication.getInstances().getPhotosDao().delete(photosList.get(i));
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Line> lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(cid)).build().list();
        try {
            for (int z = 0; z < lines.size(); z++) {
                MyApplication.getInstances().getLineDao().delete(lines.get(z));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name);
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + ".zip");*/


        //删除所有相关联的数据
        MyApplication.getInstances().getItemsDao().deleteByKey(cid);
        List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
        for (int j = 0; j < pointsList.size(); j++) {
            MyApplication.getInstances().getPointsDao().delete(pointsList.get(j));
            try {
                List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(pointsList.get(j).getId())).build().list();
                if (equipmentList.size() > 0)
                    for (int i = 0; i < equipmentList.size(); i++) {
                        MyApplication.getInstances().getEquipmentDao().delete(equipmentList.get(i));
                    }
                List<Photos> photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(pointsList.get(j).getId())).build().list();
                if (photosList.size() > 0)
                    for (int i = 0; i < photosList.size(); i++) {
                        MyApplication.getInstances().getPhotosDao().delete(photosList.get(i));
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Line> lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(cid)).build().list();
        try {
            for (int i = 0; i < lines.size(); i++) {
                MyApplication.getInstances().getLineDao().delete(lines.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ToastUtils.showShort("删除成功");
        List<Items> list = MyApplication.getInstances().getItemsDao().queryBuilder().orderDesc(ItemsDao.Properties.Id).build().list();
        adapter = new MainAdapter(context, list);

        item_listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name);
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + ".zip");

    }


    /**
     * 写在外面没法刷新试图
     **/
    private class MainAdapter extends BaseAdapter {

        @SuppressLint("SdCardPath")
        private Context context;
        private List<Items> list;
        private boolean isCheck = true;

        MainAdapter(Context context, List<Items> list) {
            this.context = context;
            this.list = list;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint({"InflateParams", "SetTextI18n"})
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.activity_main_list, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else
                viewHolder = (ViewHolder) convertView.getTag();
            final Items items = list.get(position);

            viewHolder.main_cb_switch.setVisibility(View.GONE);
            viewHolder.main_tv_name.setText(items.getName() + "");
            viewHolder.main_tv_note.setText(items.getType() + "  " + items.getVoltage());
            viewHolder.main_tv_time.setText(items.getTime() + "");
            if ("在线".equals(items.getState())) {
                viewHolder.main_iv.setBackgroundResource(R.drawable.zaixian);
                ExportUnit exportUnit = new ExportUnit();
                viewHolder.main_tv_upload.setOnClickListener(v13 -> exportUnit.SetLocalExport(context, items.getId(), items.getName()));
                viewHolder.main_tv_up.setVisibility(View.VISIBLE);
                viewHolder.main_tv_up.setOnClickListener(view -> exportUnit.SetExport(context, items.getId(), items.getName()));
            } else {
                viewHolder.main_iv.setBackgroundResource(R.drawable.bendi);
                ExportUnit exportUnit = new ExportUnit();
                viewHolder.main_tv_upload.setOnClickListener(v13 -> exportUnit.SetLocalExport(context, items.getId(), items.getName()));
                viewHolder.main_tv_up.setVisibility(View.GONE);
            }
            viewHolder.main_ibt_details.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isCheck) {
                        viewHolder.main_ibt_details.setImageResource(R.drawable.xiala);
                        viewHolder.bellow_layout.setVisibility(View.VISIBLE);
                        viewHolder.main_tv_details.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (items.getIsCheck()) {
                                    Intent intent = new Intent(context, DetailsActivity.class);
                                    intent.putExtra("details", items.getId());
                                    intent.putExtra("de_id", 2);
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(context, OnlineDetailsActivity.class);
                                    intent.putExtra("details", items.getId());
                                    intent.putExtra("de_id", 2);
                                    startActivity(intent);
                                }
                            }
                        });
                        viewHolder.main_tv_delete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startDialog(items.getId(), items.getName(), items.getState(), items.getType());
                            }
                        });

                        isCheck = !isCheck;
                    } else {
                        viewHolder.main_ibt_details.setImageResource(R.drawable.jinru);
                        viewHolder.bellow_layout.setVisibility(View.GONE);
                        isCheck = !isCheck;
                    }
                }
            });
            return convertView;
        }


        class ViewHolder {
            private TextView main_tv_name;
            private TextView main_tv_note;
            private ImageButton main_ibt_details;
            private TextView main_tv_time;
            private RelativeLayout bellow_layout;
            private TextView main_tv_upload;
            private TextView main_tv_up;
            private TextView main_tv_delete;
            private TextView main_tv_details;
            private CheckBox main_cb_switch;
            private ImageView main_iv;

            ViewHolder(View rootView) {
                this.main_tv_name = rootView.findViewById(R.id.main_tv_name);
                this.main_tv_note = rootView.findViewById(R.id.main_tv_note);
                this.main_ibt_details = rootView.findViewById(R.id.main_ibt_details);
                this.main_tv_time = rootView.findViewById(R.id.main_tv_time);
                this.bellow_layout = rootView.findViewById(R.id.below_layout);
                this.main_tv_upload = rootView.findViewById(R.id.main_tv_upload);
                this.main_tv_up = rootView.findViewById(R.id.main_tv_up);
                this.main_tv_delete = rootView.findViewById(R.id.main_tv_delete);
                this.main_tv_details = rootView.findViewById(R.id.main_tv_details);
                this.main_cb_switch = rootView.findViewById(R.id.main_cb_switch);
                this.main_iv = rootView.findViewById(R.id.main_iv);
            }

        }


    }

}
